package com.bit.bit_forum.controller;

import com.bit.bit_forum.common.AppResult;
import com.bit.bit_forum.common.ResultCode;
import com.bit.bit_forum.config.AppConfig;
import com.bit.bit_forum.exception.ApplicationException;
import com.bit.bit_forum.model.Article;
import com.bit.bit_forum.model.Board;
import com.bit.bit_forum.model.User;
import com.bit.bit_forum.service.IArticleService;
import com.bit.bit_forum.service.IBoardService;
import com.bit.bit_forum.service.impl.ArticleReplyServiceImpl;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/article")
public class ArticleController {

    @Autowired
    private IArticleService articleService;
    @Autowired
    private IBoardService boardService;
    @Autowired
    private ArticleReplyServiceImpl articleReplyServiceImpl;

    @RequestMapping("/create")
    public AppResult create(HttpServletRequest req,
                            @RequestParam("boardId") @NonNull Long boardId,
                            @RequestParam("content") @NonNull String content,
                            @RequestParam("title") @NonNull String title){
        HttpSession session = req.getSession(false);
        User user = (User)session.getAttribute(AppConfig.USER_SESSION);
        if(user.getState()==1){
            //用户已被禁言
            return AppResult.failed(ResultCode.FAILED_USER_BANNED.toString());
        }
        Board board = boardService.getById(boardId);
        if(board==null || board.getState()==1 || board.getDeleteStat()==1){
            //更新帖子数量失败
            log.info(ResultCode.FAILED_BOARD_BANNED.toString());
            return AppResult.failed(ResultCode.FAILED_BOARD_BANNED);
        }
        //创建文章对象
        Article article = new Article();
        article.setUserId(user.getId());
        article.setBoardId(board.getId());
        article.setContent(content);
        article.setTitle(title);
        articleService.create(article);
        return AppResult.success();
    }

//    根据帖子id获取详情
    @RequestMapping("/getAll")
    public AppResult getAllArticle(){
        List<Article> articles = articleService.selectAll();
        return AppResult.success(articles);
    }

    @RequestMapping("/getAllByBoardId")
    public AppResult<List<Article>> getAllByBoardId(@RequestParam(value ="boardId", required = false) Long boardId){
        List<Article> articles=null;
        if(boardId==null){
//            当为传入板块id时,获取所有帖子
            articles = articleService.selectAll();
        }else{
//            当传入的id不为空,则查询指定板块下的帖子列表
            articles = articleService.selectAllByBoardId(boardId);
        }
        if(articles==null) {
//            当未查询到时:
            articles = new ArrayList<>();
        }
        return AppResult.success(articles);
    }
//    根据帖子id获取帖子详情:
    @RequestMapping("/detail")
    public AppResult<Article> getDetail(HttpServletRequest req,
                            @RequestParam("id") @NonNull Long id){
        HttpSession session = req.getSession(false);
        if(session==null){
            //未授权:
            log.warn(ResultCode.FAILED_UNAUTHORIZED.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_UNAUTHORIZED));
        }
        User user = (User)session.getAttribute(AppConfig.USER_SESSION);
        Article article = articleService.selectDetailById(id);
//        判断登录用户是否为当前文章的作者,方便进行不同的操作:
        if(user.getId() == article.getUserId()){
            article.setOwn(true);
        }
        return AppResult.success(article);
    }

    @RequestMapping("/modify")
    public AppResult modify(HttpServletRequest req,
                       @RequestParam("id") @NonNull Long id,
                       @RequestParam("title") @NonNull String title,
                       @RequestParam("content") @NonNull String content){
        HttpSession session = req.getSession(false);
        User user = (User)session.getAttribute(AppConfig.USER_SESSION);
//        校验用户状态是否合法：
        if(user.getState()==1 || user.getDeleteStat()==1){
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        Article article = articleService.selectById(id);
//        判断帖子是否存在：
        if(article==null){
//             帖子不存在
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
      }
//        System.out.println("userId: "+user.getId());
//        System.out.println("article.userId:"+article.getUserId());
//        判断登录用户是否为帖子作者：
        if(article.getUserId() != user.getId()){
//            System.out.println("当前用户不是作者，禁止访问");
            return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
        }
//        对帖子状态校验：受否已经归档：
        if(article.getState()==1 || article.getDeleteStat()==1){
            return AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED);
        }
        articleService.modify(id,title,content);
        log.info("更新帖子成功： id:"+id +" 用户： "+user.getUsername()+ ".");
        return AppResult.success();
    }

    @RequestMapping("/likeCount")
    public AppResult addLikeCountById(HttpServletRequest req,
            @RequestParam("id") @NonNull Long id){
        HttpSession session = req.getSession(false);
        User user = (User)session.getAttribute(AppConfig.USER_SESSION);
//        对用户状态校验：
        if(user.getState()==1){
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        Article article = articleService.selectById(id);
//        对帖子校验：
        if(article==null || article.getDeleteStat()==1){
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        if(article.getState()==1){
            return AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED);
        }
        articleService.addLikeCountById(id);
        return AppResult.success();
    }
//    删除帖子
    @RequestMapping("/delete")
    public AppResult deleteById(HttpServletRequest req,
                        @RequestParam("id") @NonNull Long id){
        HttpSession session = req.getSession(false);
        User user = (User)session.getAttribute(AppConfig.USER_SESSION);
        if(user.getState()==1){
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        Article article = articleService.selectById(id);
//        对帖子进行校验：
        if(article==null || article.getDeleteStat()==1){
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        if(article.getState()==1){
            return AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED);
        }
        if(user.getId()!=article.getUserId()){
            //未授权：
            return AppResult.failed(ResultCode.FAILED_UNAUTHORIZED);
        }
        articleService.deleteById(id);
        return AppResult.success();
    }
//    获取用户的帖子列表
    @RequestMapping("/getAllByUserId")
    public AppResult selectByUserId(HttpServletRequest req,
                            @RequestParam(value="userId" ,required = false)  Long userId){
        HttpSession session = req.getSession(false);
        User user = (User)session.getAttribute(AppConfig.USER_SESSION);
        if(user==null || user.getDeleteStat()==1){
            return AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        if (userId==null) {
            userId = user.getId();
        }
        List<Article> articles = articleService.selectByUserId(userId);
        return AppResult.success(articles);
    }


}
